package cn.jhc.db;

import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.sun.org.apache.bcel.internal.generic.NEW;

import cn.jhc.Global;
import cn.jhc.bean.Article;

/**
 * CRUD(Create, Retrieve, Update, Delete)
 * @author 
 *
 */
public class ArticleDao {
	
	public static void add(QueryRunner runner, Article article) throws SQLException {
		final String sql = "insert into article(title,content,publishDate,userId) "
				+ "values(?,?,?,?)";
		runner.execute(sql, article.getTitle(), article.getContent(), article.getPublishDate(), article.getUserId());
	}
	
	public static void del(QueryRunner runner, int id) throws SQLException {
		final String sql = "delete from article where id=?";
		runner.execute(sql,id);
	}
	
	public static long count(QueryRunner runner)throws SQLException{
		final String sql="select count(id) from article";
		
		return runner.query(sql,new ScalarHandler<Long>());
		
	}
	
	public static void update(QueryRunner runner, Article newArticle) {
		
	}
	
	public static List<Article> find(QueryRunner runner, int pageNum) throws SQLException {
		final String sql = "select id, title, content, publishDate, userId from article "
				+ "order by publishDate desc limit ? offset ?";
		return runner.query(sql, new BeanListHandler<>(Article.class), 
				Global.PAGE_SIZE, pageNum * Global.PAGE_SIZE);
	}
	
	public static Article findOne(QueryRunner runner, int id) {
		return null;
	}
}